local UIBase = require("view.UIBase")
local ShopView = class("ShopView", UIBase)
local ShopViewHelper = require("view.shop.ShopViewHelper")

local MAX_CARD = 5

function ShopView:ctor()
    local resource = {
        path = "Prefabs/View/Shop",
        name = "ShopView",
        canvas = 2
    }
    ShopView.super.ctor(self, resource)
end

function ShopView:start()
    self._btnTabItem.onClick:AddListener(handler(self, self._onTabItemClick))
    self._btnTabEquip.onClick:AddListener(handler(self, self._onTabEquipClick))
    self._btnTabMagic.onClick:AddListener(handler(self, self._onTabMagicClick))
    self._btnClose.onClick:AddListener(handler(self, self._onBtnCloseClick))

    self._listView:SetTemplate(
        handler(self, self._onItemUpdate),
        handler(self, self._onValueChange),
        handler(self, self._onItemTouch)
    )
    self:_updateTab(1)
end

function ShopView:_updateTab(index)
    if self._selectIndex == index then
        return
    end
    self._textTitle.text = Lang.get("lang_shop_tab_" .. index)
    self._selectIndex = index
    self._dataList = ShopViewHelper.getShopListByTab(self._selectIndex)
    local count = math.ceil(#self._dataList / MAX_CARD)
    self._listView:ReSize(count)
end

function ShopView:_onTabItemClick()
    self:_updateTab(1)
end

function ShopView:_onTabEquipClick()
    self:_updateTab(2)
end

function ShopView:_onTabMagicClick()
    self:_updateTab(3)
end

function ShopView:_onItemUpdate(item, index)
    local startIndex = index * MAX_CARD + 1
    local endIndex = startIndex + MAX_CARD - 1
    local lines = {}
    for i = startIndex, endIndex do
        local data = self._dataList[i]
        if data then
            table.insert(lines, data)
        end
    end
    item:updateUI(lines)
end

function ShopView:_onValueChange()
end

function ShopView:_onItemTouch()
end

function ShopView:_onBtnCloseClick()
    self:close()
end

return ShopView
